<?php

namespace App\Services\Stats\User;

use App\Services\Service;
use App\Services\Traits\DatabaseMysql;
use App\Models\Admin\Stats\User\Day;
use App\Models\Admin\Stats\User\Week;
use App\Models\Admin\Stats\User\Month;
use Helper\Timed;

class PlayerService extends Service
{
    use DatabaseMysql;

    /**
     * 统计图【天】
     *
     * @param \Illuminate\Http\Request $request
     * @return array
     */
    public function day($request)
    {
        list($timed, $timedEnd) = $this->getParamArray($request, 'datetime');

        return $this->stats(
            $request, Day::dbTable(),
            Timed::getDayCurrentTimed($timed),
            Timed::getDayCurrentTimed($timedEnd)
        );
    }

    /**
     * 统计图【周】
     *
     * @param \Illuminate\Http\Request $request
     * @return array
     */
    public function week($request)
    {
        $datetime = $request->input('datetime');

        return $this->stats(
            $request, Week::dbTable(),
            Timed::getWeekCurrentTimed(Timed::getYearCurrentTimed($datetime)),
            Timed::getYearNextTimed($datetime)
        );
    }

    /**
     * 统计图【月】
     *
     * @param \Illuminate\Http\Request $request
     * @return array
     */
    public function month($request)
    {
        list($timed, $timedEnd) = $this->getParamArray($request, 'datetime');

        return $this->stats(
            $request, Month::dbTable(),
            Timed::getMonthCurrentTimed($timed),
            Timed::getMonthCurrentTimed($timedEnd)
        );
    }

    /**
     * 获取统计数据
     *
     * @param \Illuminate\Http\Request $request
     * @param \Illuminate\Database\Query\Builder $query
     * @param int $timed
     * @param int $timedEnd
     * @return array
     */
    protected function stats($request, $query, $timed, $timedEnd)
    {
        // 筛选【平台】
        $this->makeWhereParamOrg($request, $query);
        // 查询数据
        $stats = $query->selectRaw(implode(',', [
            'timed',
            'SUM(u_game) AS u_game',
            'SUM(u_sign) AS u_sign',
            'SUM(nu_game) AS nu_game',
            'SUM(nu_sign) AS nu_sign',
        ]))
            ->where('timed', '>=', $timed)
            ->where('timed', '<', $timedEnd)
            ->groupBy('timed')
            ->orderBy('timed')
            ->get();

        return [
            'stats' => $stats,
            'datetime' => [$timed, $timedEnd]
        ];
    }
}
